`timescale 1ns/1ps

module MEM_tb;

    // 信号声明
    reg clk;                // 时钟信号
    reg mem_write_en;           // 写使能信号
    reg rst_n;              // 复位信号（低电平有效）
    wire [15:0] MBR_2_MEM;      // 数据输入
    wire [7:0] MAR_2_MEM;       // 地址输入
    wire [15:0] MEM_2_MBR; // 数据输出

    // 被测模块实例化
    MEM MEM_inst(
        .clk(clk),
        .write_en(mem_write_en),
        .MBR_in(MBR_2_MEM),
        .MAR_in(MAR_2_MEM),
        .data_2_MBR(MEM_2_MBR)
    );
    reg MAR_in_en;
    reg MAR_out_en;
    wire [15:0] data_bus;
    MAR MAR_inst(
            .clk(clk),
            .data_in_en(MAR_in_en),
            .data_out_en(MAR_out_en),
            .data_bus(data_bus),
            .rst_n(rst_n),
            .data_2_MRMORY(MAR_2_MEM)
        );
    reg MBR_in_en;
    reg MBR_out_en;
    reg read_form_MEM_en;
    MBR MBR_inst (
        .clk(clk),
        .data_in_en(MBR_in_en),
        .data_out_en(MBR_out_en),
        .data_bus(data_bus),
        .rst_n(rst_n),
        .read_form_MEM_en(read_form_MEM_en),
        .data_form_MRMORY(MEM_2_MBR),
        .data_2_MEM(MBR_2_MEM)
    );

    reg bus_write_en;
    reg [15:0] bus_reg;
    assign data_bus =bus_write_en ? bus_reg : 16'hzzzz;
    wire [15:0] MAR_reg;
    assign MAR_reg = MAR_inst.data_reg;
    wire [15:0] MBR_reg;
    assign MBR_reg = MBR_inst.data_reg;
    // 时钟生成（50MHz，周期20ns）
    always #5 clk = ~clk;
    initial begin
        MAR_inst.data_reg = 8'h22;
        clk = 1'b0;
        rst_n = 1'b0;
        MAR_in_en = 1'b0;
        MAR_out_en = 1'b0;
        MBR_in_en = 1'b0;
        MBR_out_en = 1'b0;
        read_form_MEM_en = 1'b0;
        mem_write_en = 1'b0;
        bus_write_en = 1'b0;
        bus_reg = 16'h0000;

        #20 
        rst_n = 1'b1;
        bus_reg = 16'h1234;
        bus_write_en = 1'b1;        
        MBR_in_en = 1'b1; //bus->MBR
        #10
        bus_reg= 16'h0011;
        MBR_in_en = 1'b0; 
        MAR_in_en = 1'b1;//bus->MAR
        #10
        MAR_in_en = 1'b0;
        mem_write_en = 1'b1;//MBR->MEM
        #10
        mem_write_en = 1'b0;
        bus_reg = 16'h0000;
        MBR_in_en = 1'b1;//bus->MBR
        #10
        MBR_in_en = 1'b0;
        read_form_MEM_en = 1'b1;//MEM->MBR
        #10
        read_form_MEM_en = 1'b0;
        #10
        $finish;


    end




endmodule

